namespace Nice157Advices.Advices
{
    /// <summary>
    /// 39、了解委托的实质
    /// 40、使用event关键字为委托施加保护
    /// </summary>
    public static class _39_40
    {
        /**
         * 委托是方法指针
         * 委托是一个类，当对其进行实例化的时候，要将引用方法作为它的构造方法的参数
         */

        public static void Go ()
        {
            var uploader = new FileUploader ();
            uploader.FileUploaded += (progress) => System.Console.Write($"{progress} ");

            uploader.Upload (); // 只能通过 FileUploader 类对象的 Upload 方法调用 FileUploaded
        }

        private class FileUploader
        {
            public delegate void FileUploadedHandler (int progress);
            public event FileUploadedHandler FileUploaded;
            /**
             * 使用 event 关键字为委托施加保护
             * 以下几种情况会在编译期间被阻止：
             * 1.uploader.FileUploaded = null
             * 2.uploader.FileUploaded = (progress) => {};
             * 3.uploader.FileUploaded (10);
             */

            public void Upload ()
            {
                int fileProgress = 100;
                while (fileProgress > 0)
                {
                    fileProgress--;
                    if (FileUploaded != null)
                    {
                        FileUploaded (fileProgress);
                    }
                }
            }
        }
    }
}